package com.kelvin.manage.service.impl;

import com.kelvin.manage.common.Asserts;
import com.kelvin.manage.mapper.StudentMapper;
import com.kelvin.manage.mapper.TeacherMapper;
import com.kelvin.manage.mapper.UserMapper;
import com.kelvin.manage.model.Student;
import com.kelvin.manage.model.Teacher;
import com.kelvin.manage.model.User;
import com.kelvin.manage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public int register(String username, String password, String confirmPassword,String role) {
        log.info("用户注册请求，用户名：{}，角色：{}",username,role);
        // 验证两次输入的密码是否一致
        if (!password.equals(confirmPassword)) {
            log.warn("用户注册失败，原因：两次密码输入不一致，用户名：{}", username);
            Asserts.fail("两次密码的输入不一致");
        }
        // 验证是否已经存在该用户
        if(userMapper.getUserByUsername(username)!=null){
            log.warn("用户注册失败，原因：用户名已存在，用户名：{}", username);
            Asserts.fail("该用户已存在");
        }
        // 没有该用户进行添加操作
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setRole(role);
        int result=userMapper.insertUser(user);

        if(role.equals("TEACHER")){
            Teacher teacher=new Teacher();
            teacher.setUser_id(user.getId());
            teacherMapper.insertTeacher(teacher);
        }
        else if(role.equals("STUDENT")){
            Student student=new Student();
            student.setUser_id(user.getId());
            studentMapper.insertStudent(student);
        }

        // 避免密码泄露
        user.setPassword(null);
        log.info("用户注册成功，用户名：{}，角色：{}", username, role);
        return result;
    }

    @Override
    public int login(String username, String password) {
        // 验证是否已经存在该用户
        User user=userMapper.getUserByUsername(username);
        if(user==null){
            Asserts.fail("该用户名不存在，请先注册");
        }
        if(!passwordEncoder.matches(password,user.getPassword())){
            Asserts.fail("密码不正确");
        }

        List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(user.getRole()));
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, authorities);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        return 1;
    }

}
